<?php

class Light_Service_Proxy
{
    /**
     * @var mixed
     */
    protected $_service;

    /**
     * @var string
     */
    protected $_method;

    /**
     * @var array
     */
    protected $_params = array();

    /**
     * @var boolean
     */
    protected $_isExecuted = false;

    /**
     * @param mixed $_service
     * @param array $_params
     */
    public function __construct($_service, array $_params = array())
    {
        if (is_array($_service)) {
            if (empty($_service)) {
                throw new Light_Exception("Service param cannot be empty array");
            }
            $this->setService($_service[0]);
            if (isset($_service[1])) {
                $this->setMethod($_service[1]);
            }
        } else {
            $this->setService($_service);
        }

        $this->setParams($_params);
    }

    /**
     * @param boolean $new
     * @return Light_Service_Abstract
     */
    public function execute($new = false)
    {
        $service = $this->getService();
        $method  = $this->getMethod();
        $params  = $this->getParams();

        if ($new || $this->_isExecuted === false) {

            if (is_string($service)) {
                $service = new $service();
            } else if ($new) {
                $tmp = get_class($service);
                $service = new $tmp();
            }

            if (!$service instanceof Light_Service_Abstract) {
                throw new Light_Exception("Service '" . get_class($service) . "' is not instance of Light_Service_Abstract");
            }

            if ($method !== null) {
                call_user_func_array(array($service, $method), $params);
            }

            $this->setService($service);

            $this->_isExecuted = true;
        }

        return $service;
    }

	/**
     * @return string $_service
     */
    public function getService ()
    {
        return $this->_service;
    }

	/**
     * @param string $_service
     * @return Light_Service_Proxy
     */
    public function setService ($_service)
    {
        $this->_service = $_service;

        return $this;
    }

	/**
     * @return string $_method
     */
    public function getMethod ()
    {
        return $this->_method;
    }

	/**
     * @param string $_method
     * @return Light_Service_Proxy
     */
    public function setMethod ($_method)
    {
        $this->_method = $_method;

        return $this;
    }
	/**
     * @return array $_params
     */
    public function getParams ()
    {
        return $this->_params;
    }

	/**
     * @param array $_params
     * @return Light_Service_Proxy
     */
    public function setParams ($_params)
    {
        $this->_params = $_params;

        return $this;
    }
}